<template>
  <div class="clearfix">
    <a-upload list-type="picture-card" :file-list="fileList" @change="change" :before-upload="beforeUpload">
      <div v-if="fileList.length < 1">
        <a-icon type="plus" />
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { uploadPic } from '@/api/login'

export default {
   name: 'uploadImg',
  props: ['defaultImg'],
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
    }
  },
  methods: {
    beforeUpload(file) {
      this.fileList = []
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png图片格式！')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('只能上传10MB以内的图片!')
        return
      }
      this.$emit('loading',true)
      const formData = new FormData()
      formData.append('file', file)
      // formData.append('school_id', this.$store.state.user.school)
      // 输出
      uploadPic(formData).then(res => {
        this.previewImage = res.url
        this.fileList.push({
          name: res.path,
          uid: '-1',
          url: res.url
        })
        this.$emit('imgUrl', res.path)
        this.$emit('imgUrl1', res.url)
      }).finally(()=>{
      this.$emit('loading',false)

      })
      return false
    },
    handleCancel() {
      this.previewVisible = false
    },
    getDefault() {
      if (this.defaultImg) {
        this.previewImage = this.defaultImg
        this.fileList.push({
          name: this.defaultImg,
          uid: '-1',
          url: this.defaultImg
        })
        this.$forceUpdate()
      }
    },
    setDefault(data){
        this.previewImage = data
        this.fileList.push({
          name: data,
          uid: '-1',
          url: data
        })
    },
    change({fileList}){
      if(fileList.length==0){
        this.fileList = []
        this.$emit('remove')
      }
    },
  },
  created() {
      this.getDefault()
      console.log(this.fileList,99)
  }
}
</script>
<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

</style>